const Koa = require('koa');
const app = new Koa();
const path = require('path');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const session = require('koa-session');
const render = require('koa-art-template');
const responseTime = require('koa-better-response-time');
const requestId = require('koa-better-request-id');
const logger = require('./middleware/logger');

// 数据库初始化文件
require('./init')();

const COOKIE_SESSION_CONF = require('./conf/cookie-session');

// error handler
onerror(app, {
  all: (err, ctx) => {
    const { status, message } = err;
    ctx.errorMsg = {
      status,
      message,
      requestId: ctx.response.headers['x-request-id'],
    };
    ctx.logger.error('errorMsg', ctx);
    ctx.body = {
      message
    };
  }
});

app.use(async function (ctx, next) {
  await next();
  ctx.logger.info('httpMsg', ctx);
});
app.use(logger());
app.use(responseTime());
app.use(requestId());

app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(require('koa-static')(__dirname + '/public'));

render(app, {
  root: path.join(__dirname, 'arts'),
  extname: '.art',
  debug: process.env.NODE_ENV !== 'production'
});

app.keys = ['Xp2Yf{4Zz+', '!w7*GxQd^1'];
app.use(session(COOKIE_SESSION_CONF, app));

// routes
require('./utils/initRouter')(app);

module.exports = app;
